"""B站热榜爬虫"""
import asyncio
import json
import logging
from datetime import datetime
from typing import Dict, Any, List, Optional

from .base_spider import BaseSpider

logger = logging.getLogger(__name__)


class BilibiliHotSpider(BaseSpider):
    """B站热榜爬虫
    
    爬取B站热门视频榜单
    """
    
    # B站热榜API
    BILIBILI_RANKING_API = "https://api.bilibili.com/x/web-interface/ranking/v2"
    
    def __init__(self):
        """初始化B站爬虫"""
        super().__init__(name="BilibiliHotSpider")
        
        # 更新请求头
        self.headers.update({
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Origin': 'https://www.bilibili.com',
            'Referer': 'https://www.bilibili.com/v/popular/rank/all'
        })
    
    async def fetch_hot_videos(self, rid: int = 0, limit: int = 100) -> List[Dict[str, Any]]:
        """获取热门视频
        
        Args:
            rid: 分区ID，0为全站
            limit: 获取数量
            
        Returns:
            热门视频列表
        """
        try:
            params = {
                'rid': rid,  # 0=全站，1=动画，3=音乐，4=游戏，5=娱乐等
                'type': 'all'  # all=全部，origin=原创
            }
            
            response = await self.fetch(self.BILIBILI_RANKING_API, params=params)
            if not response:
                logger.error("获取B站热榜失败")
                return []
            
            data = json.loads(response)
            
            if data.get('code') != 0:
                logger.error(f"B站API错误: {data.get('message', 'Unknown error')}")
                return []
            
            hot_list = []
            videos = data.get('data', {}).get('list', [])
            
            for idx, video in enumerate(videos[:limit], 1):
                hot_item = {
                    'rank': idx,
                    'title': video.get('title', ''),
                    'author': video.get('owner', {}).get('name', ''),
                    'bvid': video.get('bvid', ''),
                    'url': f"https://www.bilibili.com/video/{video.get('bvid', '')}",
                    'pic': video.get('pic', ''),
                    'desc': video.get('desc', ''),
                    'duration': video.get('duration', 0),
                    'pubdate': datetime.fromtimestamp(video.get('pubdate', 0)).isoformat() if video.get('pubdate') else None,
                    'stats': {
                        'view': video.get('stat', {}).get('view', 0),
                        'danmaku': video.get('stat', {}).get('danmaku', 0),
                        'reply': video.get('stat', {}).get('reply', 0),
                        'favorite': video.get('stat', {}).get('favorite', 0),
                        'coin': video.get('stat', {}).get('coin', 0),
                        'share': video.get('stat', {}).get('share', 0),
                        'like': video.get('stat', {}).get('like', 0)
                    },
                    'score': video.get('score', 0),
                    'platform': 'bilibili',
                    'source': 'bilibili',
                    'fetch_time': datetime.now()
                }
                
                hot_list.append(hot_item)
            
            logger.info(f"成功获取 {len(hot_list)} 条B站热门视频")
            return hot_list
            
        except Exception as e:
            logger.error(f"获取B站热榜失败: {e}")
            return []
    
    async def parse(self, html: str, url: str = None) -> List[Dict[str, Any]]:
        """解析响应（主要用于兼容基类）
        
        Args:
            html: 响应内容
            url: 请求URL
            
        Returns:
            解析结果
        """
        try:
            data = json.loads(html)
            if isinstance(data, dict) and 'data' in data:
                return data.get('data', {}).get('list', [])
        except:
            pass
        return []


    async def crawl_hot(self) -> List[Dict[str, Any]]:
        """统一接口：获取热门视频"""
        return await self.fetch_hot_videos()

async def main():
    """测试主函数"""
    logging.basicConfig(level=logging.INFO)
    
    async with BilibiliHotSpider() as spider:
        # 获取全站热门
        hot_videos = await spider.fetch_hot_videos(limit=10)
        
        if hot_videos:
            print(f"\n=== B站热榜测试结果 ===")
            print(f"获取到 {len(hot_videos)} 条热门视频")
            
            # 显示前5条
            for video in hot_videos[:5]:
                print(f"{video['rank']}. {video['title']}")
                print(f"   UP主: {video['author']}")
                print(f"   播放量: {video['stats']['view']:,} | 弹幕: {video['stats']['danmaku']:,}")
        else:
            print("未能获取B站热榜数据")
        
        return len(hot_videos) > 0


if __name__ == "__main__":
    result = asyncio.run(main())
    exit(0 if result else 1)